import React, { Component } from 'react'
import '../../src/assets/css/cart.css'
import '../../src/assets/css/reset.css'
import { Cartlist, Cartdelete } from '../request/api'
import { Dialog, List, SwipeAction, Toast } from 'antd-mobile'
import { Link } from 'react-router-dom'
export default class cart extends Component {
    constructor() {
        super()
        this.state = {
            goodList: [],
            goodsList: [],
            checkAll: 1,
            allprice:0
        }
    }
  
    componentDidMount() {
        this.fn()
    }
    // componentDidUpdate(){
    //  console.log(  JSON.parse( sessionStorage.getItem("islogin")).uid );
    // }
    fn() {
        
        Cartlist({ uid: sessionStorage.getItem("islogin")?JSON.parse( sessionStorage.getItem("islogin")).uid:[]}).then(res => {
            console.log(res);
            if (res.code == 200) {
                this.setState({
                    goodList: res.list[0].content? res.list[0].content:[],
                    goodsList: res.list[1].content?res.list[1].content:[]
                })

            }
        })
    }

    // 价格
    all() {
        let sum = 0
        let sums = 0
        this.state.goodList.forEach(item => {

            if (item.status == 1) {
                sum += item.price * item.num
            }
        })
        this.state.goodsList.forEach(item => {
            if (item.status == 1) {
                sums += item.price * item.num;
            }
        })
        let z = sum + sums
        return (z.toFixed(2))

    }
    // 结算
    jiesuan(e){
      
        // 判断用户是否选择了一件商品
        if(this.state.goodsList.some(item=> item.status)){
            // 先获取用户购买的数量
            let num = 0;
            let val = '';//id
            let  goods = [];
            this.state.goodsList.map(item=>{
                if(item.status){
                    num += item.num
                    val += `,${item.id}`
                    goods.push(item)
                }
            });
            // 定义一个对象去接收几个必要条件
            let objInfo = {
                countminey:this.all(),
                countnumber:num,
                idstr:val.slice(1)
            }

            sessionStorage.setItem('objInfo',JSON.stringify(objInfo))
            sessionStorage.setItem('goodsList',JSON.stringify(this.state.goodsList))
            
        }else{
            e.preventDefault();
            alert('至少选择一件商品')
        }
    }
    // 减
    jian(i, type) {
        if (type == 2) {
            this.state.goodList[i].num--
            this.state.goodList[i].num = Math.max(1, this.state.goodList[i].num)
        } else {
            this.state.goodsList[i].num--
            this.state.goodsList[i].num = Math.max(1, this.state.goodsList[i].num)
        }
        this.setState({

        })
    }
    // 加
    jia(i, type) {
        if (type == 2) {
            this.state.goodList[i].num++
        } else {
            this.state.goodsList[i].num++
        }
        this.setState({

        })
    }
    // 全选
    setCheck() {
        if (this.state.checkAll == 1) {
            this.state.checkAll = 2
        } else {
            this.state.checkAll = 1
        }
        this.state.goodList.map(item => {
            item.status = this.state.checkAll
        })
        this.state.goodsList.map(item => {
            item.status = this.state.checkAll
        })
        this.setState({

        })

    }
    // 单选
    changeOne(i, type) {

        if (type == 2) {
            if (this.state.goodList[i].status == 1) {
                this.state.goodList[i].status = 2
            }
            else {
                this.state.goodList[i].status = 1
            }
        }
        else {
            if (this.state.goodsList[i].status == 1) {
                this.state.goodsList[i].status = 2
            } else {
                this.state.goodsList[i].status = 1
            }
        }
        let a = this.state.goodList.every(item => {
            return item.status == 1
        })
        let b = this.state.goodsList.every(item => {
            return item.status == 1
        })
        if (a && b) {
            this.state.checkAll = 1
        } else {
            this.state.checkAll = 2
        }
        this.setState({

        })
    }
    render() {
        let { goodList, goodsList, checkAll } = this.state
        return (
            <div id='cart'>

                <div className='header'>
                    <p>
                        <span>&lt;</span>
                        <span className='g'> 购物车</span>
                    </p>
                    <p >
                        <span className='bbg'>全部（20）</span>
                        <span className='bbg'>降价（4）</span>
                        <span className='bbg'>常规（2）</span>
                        <span className='bbg'>分类</span>
                    </p>
                </div>
            
                <div className='content'>

                    <input type="radio" />
                    <span>品牌精选</span>
                    <p className='yi'>
                        <span>已免运费</span>
                        <span>|</span>
                        <span>领卷</span>
                    </p>

                    <ul>
                        {goodsList.map((item, i) => {
                            return (
                                <li key={item.id} >

                                    <List>
                                        <SwipeAction
                                            // ref={ref}
                                            closeOnAction={false}
                                            closeOnTouchOutside={false}
                                            rightActions={[
                                                {
                                                    key: 'delete',
                                                    text: '删除',
                                                    color: 'danger',
                                                    onClick: async () => {
                                                        const result = await Dialog.confirm({
                                                            content: '确定要删除吗？',
                                                        })
                                                        if (result) {
                                                            Cartdelete({ id: item.id }).then(res => {
                                                                if (res.code == 200) {
                                                                    Toast.show({ content: '删除成功', position: 'bottom' })
                                                                }
                                                            })
                                                            this.fn()

                                                        } else {
                                                            Toast.show({ content: '点击了取消', position: 'bottom' })
                                                        }
                                                    },
                                                },
                                            ]}
                                        >
                                            <List.Item

                                            >

                                                <div className='shang'>
                                                    <div>
                                                        <input type="checkbox" checked={item.status == 1 ? true : false} onChange={() => this.changeOne(i, item.type)} />

                                                        <img src={item.img} alt="" />

                                                    </div>
                                                    <div className='xia'>
                                                        <p className='biao'>{item.goodsname}</p>

                                                        <p className='jie'>敏感肌可用，控油祛痘、男女可...</p>
                                                        <select >
                                                            <option value="0">粉色50ML</option>
                                                            <option value="1">1</option>
                                                            <option value="2">2</option>
                                                            <option value="3">3</option>
                                                            <option value="4">4</option>
                                                        </select>
                                                        <p className='jiang'>
                                                        比加入时降低￥5
                                                        </p>
                                                        <span className='xian'>￥{item.price}</span>

                                                        <span className='yuan'>￥1099</span>
                                                        <div className='jian'>
                                                            <span className='j' onClick={() => this.jian(i, item.type)}>-</span>

                                                            <span className='s' >{item.num}</span>


                                                            <span className='ji' onClick={() => this.jia(i, item.type)}>+</span>
                                                        </div>
                                                    </div>
                                                </div>

                                            </List.Item>
                                        </SwipeAction>
                                    </List>
                                </li>
                            )
                        })}

                    </ul>
                </div>
                <div className='zhan'></div>
                <div className='fu' >

                    <div className='qu'>  <input type="checkbox" onChange={() => this.setCheck()} checked={checkAll == 1 ? true : false} />
                        {/* */}
                        <span >全选 </span></div>
                    <div className='he'>
                        <p className='zuo'><span>合计</span><span className='jia'>￥{this.all()}</span></p>
                        <p className='zuos'><span>以免运费</span><span className='jias'>已优惠￥200元</span></p>
                    </div>
                    <div>
                        <Link to='/order'>
                        <button onClick={()=>this.jiesuan()}>去结算</button>
                        </Link>
                      
                    </div>
                </div>
            </div>
        )
    }
}
